package com.funsolution.taskhey.webservice;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.inject.Inject;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.funsolution.taskhey.domain.Person;
import com.funsolution.taskhey.manager.json.JsonManager;
import com.funsolution.taskhey.manager.person.PersonManager;

public class PersonRest {
    @EJB
    private PersonManager personManager;
    @Inject
    private JsonManager jsonMananger;
    @Inject
    private transient Logger logger;

    @POST
    @Path("/register")
    @Produces(value = { MediaType.APPLICATION_JSON })
    public Response registration(@FormParam("username") String username, @FormParam("password") String password, @FormParam("firstname") String firstname, @FormParam("secondname") String secondname, @FormParam("email") String email, @FormParam("birth_date") String birthDate) {

	Person person = personManager.findByUsername(username);
	if (person == null) {
	    person = new Person();
	    try {
		person.setUsername(username);
		person.setPassword(password);
		person.setFirstName(firstname);
		person.setSecondName(secondname);
		person.setEmail(email);
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

		person.setBirthDate(dateFormat.parse(birthDate));
		logger.info(person.toString());
		personManager.save(person);

	    } catch (ParseException e) {
		return Response.status(Response.Status.BAD_REQUEST).entity(jsonMananger.createJsonMessage("Internal server error", null).toString()).build();
	    }
	} else {
	    return Response.status(Response.Status.BAD_REQUEST).entity(jsonMananger.createJsonMessage("User with username :"+username+" allready exists", null).toString()).build();

	}

	return Response.status(Response.Status.OK).entity(jsonMananger.createJsonMessage("User sucessffuly created", person.getJson().toString()).toString()).build();
    }
    
    @POST
    @Path("/login")
    public Response login(@FormParam("username") String username,@FormParam("password") String pasword){
	return Response.status(Response.Status.OK).build();
	
    }

}
